<?php
/**
 * Description of PdoDb
 *
 * @author LuoYingBin
 */
class PdoDb {
    /**
     * @var PDO
     */
    protected $pdo;
    
    /**
     * @var PDOStatement
     */
    protected $stm;
    protected $fetchMod;
    public function __construct() {
        $this->fetchMod=PDO::FETCH_ASSOC;
    }
    public function connectMysql($host,$db,$user,$pwd,$port=null){
        $dsn="mysql:host={$host};dbname={$db}";
        if(isset($port)){
            $dsn.=";port={$port}";
        }
        $this->pdo=new PDO($dsn, $user, $pwd,array(
            PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION
        ));
    }
    public function connectOracle($db,$user,$pwd){
        $dsn="oci:dbname=".$db;
        $this->pdo=new PDO($dsn, $user, $pwd,array(
            PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION
        ));
    }
    public function setFetchMod($mod){
        $this->fetchMod=$mod;
    }
    public function beginTrans(){
        $this->pdo->beginTransaction();
    }
    public function commit(){
        $this->pdo->commit();
    }
    public function rollBack(){
        $this->pdo->rollBack();
    }
    public function lastInsertId($sequenceName=null){
        return $this->pdo->lastInsertId($sequenceName);
    }
    public function query($sql,$params=null){
        $this->queryStm($sql,$params);
        return $this->stm->fetchAll($this->fetchMod);
    }
    public function queryOne($sql,$params=null){
        $this->queryStm($sql,$params);
        return $this->fetchOne();
        
    }
    public function queryCursor($sql,$params=null){
        $this->queryStm($sql,$params);
    }
    protected  function queryStm($sql,$params=null){
        $ps=$this->convertParams($params);
        $this->stm=$this->pdo->prepare($sql);
        $this->stm->execute($ps);
    }
    
    protected function convertParams($params){
        if($params==null) {
            return null;
        }
        if(is_array($params)){
            $ps=array();
            foreach($params as $key => $val){
                $ps[$key]=!is_numeric($val) && empty($val)?
                        null:$val;
            }
            return $ps;
        }
        return null;
    }
    public function fetchOne(){
        return $this->stm->fetch($this->fetchMod);
    }

    public function exec($sql,$params=null){
        $ps=$this->convertParams($params);
        $this->stm=$this->pdo->prepare($sql);
        $b=$this->stm->execute($ps);
        if($b){
            return $this->stm->rowCount();
        }
        return 0;
    }
    
    public function getErr(){
        return $this->pdo->errorInfo();
    }
    public function getStmErr(){
        return $this->stm->errorInfo();
    }
}